<?php

namespace app\admin\controller;

use app\admin\controller\Utils\FileImport;
use app\app\model\ProjectModel;
use app\BaseController;
use app\app\model\ProjectTDModel;
use app\Request;
use PhpOffice\PhpSpreadsheet\Reader\Exception;
use think\exception\ValidateException;
use think\facade\Filesystem;


class ProjectPower extends BaseController
{
    public function list()
    {
        $project_name = input('project_name','');
        $project_id = input('project_id','');
        $page_size = input('pageSize', '20');

        $where = [];
        if ($project_name) {
            $where[] = ['project_name', 'like', '%' . $project_name . '%'];
        }
        if ($project_id) {
            $where[] = ['project_id', '=', $project_id];
        }
        $list = ProjectTDModel::where($where)->paginate([
                'list_rows'=> $page_size,
                'var_page' => 'pageNum',
            ]);
        $this->success('success', $list);
    }

    public function add(Request $request)
    {
        $data = $request->param();
        $model = new ProjectTDModel();
        $data['oper_time'] = date('Y-m-d H:i:s', time());
        $result = $model->save($data);
        if ($result !== false) {
            $this->success('添加成功!');
        } else {
            $this->error("保存失败！");
        }
    }

    public function update(Request $request)
    {
        $data = $request->param();
        $id = $request->param('id', 0, 'intval');
        $result = ProjectTDModel::strict(false)->where('id', $id)->update($data);
        if ($result !== false) {
            $this->success("保存成功！");
        } else {
            $this->error("保存失败！");
        }
    }


    public function delete(Request $request)
    {
        $data = $request->param();
        $ids = $data['ids'];
        ProjectTDModel::destroy(function($query) use ($ids){
            $query->where('id', 'in', $ids);
        });
    }


    /**
     * 停电计划导入
     * @return string|void
     * @author Kongkai
     * @date 2022-03-11
     */
    public function importData()
    {
        // 获取表单上传文件
        if (empty(request()->file('file'))) {
            $this->error("请上传文件！");
        }

        try {
            $file = request()->file();
        } catch (\Exception $e) {
            $this->error("文件上传失败");
        }

        try {
            // 验证文件大小，名称等是否正确
            validate(['file' => 'filesize:52428800|fileExt:xls,xlsx'])
                ->check($file);
        } catch (ValidateException $e) {
            $this->error($e->getMessage());
        }

        $file_path = root_path('runtime') . 'storage/';
        $file_name = Filesystem::putFile(date('Ymd') . '/' . 'power', $file['file']);

        try {
            $data = (new FileImport())->ExcelImport($file_path . $file_name);
        } catch (Exception|\PhpOffice\PhpSpreadsheet\Exception $e) {
            $this->error($e->getMessage());
        }

        $insert_array = [];
        foreach ($data as $k => $v) {
            if ($k == 0) continue;

            $project = ProjectModel::where('project_no', $v[0])->find();
            if (empty($project)) continue;

            $project_id = $project->id;

            $insert_array[] = [
                'project_no' => $v[0] ?: null,
                'project_id' => $project_id,
                'td_year' => $v[1] ?: null,
                'sb_name' => $v[2] ?: null,
                'td_place' => $v[3] ?: null,
                'start_date' => date('Y-m-d H:i:s', strtotime($v[4])) ?: null,
                'end_date' => date('Y-m-d H:i:s', strtotime($v[5])) ?: null,
                'td_day' => $v[6] ?: null,
                'work_detail' => $v[7] ?: null,
                'gc_fl' => $v[8] ?: null,
                'gc_xz' => $v[9] ?: null,
                'sb_type' => $v[10] ?: null,
                'work_dw' => $v[11] ?: null,
                'is_qd' => $v[12] ?: null,
                'remark' => $v[13] ?: null,
                'is_cb' => $v[14] ?: null,
                'xg_jl' => $v[15] ?: null,
                'xtc_yj' => $v[16] ?: null,
                'gx_reason' => $v[17] ?: null,
                'risk_desc' => $v[18] ?? null,
                'is_high_risk' => $v[19] ?? null,
                'factory_stations' => $v[20] ?? null,
            ];
        }

        try {
            (new ProjectTDModel())->insertAll($insert_array);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('上传成功');
    }
}
